package com.hnu.store.config;

import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 配置跨域和拦截
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

  /**
   * 开启跨域
   * @param registry CorsRegistry
   */
  @Override
  public void addCorsMappings(CorsRegistry registry) {
    //  设置允许跨域的路由
    registry.addMapping("/**")
        //  设置允许跨域请求的域名
        .allowedOriginPatterns("*")
        //  是否允许携带cookie参数
        .allowCredentials(true)
        //  设置允许的方法
        .allowedMethods("*")
        //  跨域允许时间
        .maxAge(3600);
  }

  private TokenInterceptor tokenInterceptor;

  /**
   * 构造函数，构造一个tokenInterceptor
   * @param tokenInterceptor 拦截器
   */
  public WebMvcConfig(TokenInterceptor tokenInterceptor){
    this.tokenInterceptor = tokenInterceptor;
  }

  /**
   * 排除拦截，除了注册登录(此时还没token)，其他都拦截
   * @param registry InterceptorRegistry
   */
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    List<String> excludePath = new ArrayList<>();

    //  登录
    excludePath.add("/user/register");
    //  注册
    excludePath.add("/user/login");
    //  发送验证码
    excludePath.add("/user/sendCaptcha");
    excludePath.add("/user/passwordCaptcha");
    //  待补充
    excludePath.add("/work/downloadNft");
    excludePath.add("/user/getAvatar");
    excludePath.add("/sale/getImg");
    excludePath.add("/news/getImg");
    excludePath.add("/case/getImg");
    excludePath.add("/user/getCertification");

    registry.addInterceptor(tokenInterceptor)
        .addPathPatterns("/**")
        .excludePathPatterns(excludePath);
    WebMvcConfigurer.super.addInterceptors(registry);
  }

}

